package com.ziq.zcamp.manager

import android.app.Activity
import android.content.Context
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.ziq.base.extension.launchWithTryAsyncGlobal
import com.ziq.base.extension.launchWithTryAsynchronous
import com.ziq.zcamp.api.request.post.PostSubjectListParam
import com.ziq.zcamp.api.request.post.PostingRecordParam
import com.ziq.zcamp.api.respond.post.PostSubjectListRespond
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.bean.post.*
import com.ziq.zcamp.dialog.PostTypeSelectorDialog
import com.ziq.zcamp.post.DynamicDetailActivity
import com.ziq.zcamp.post.PublishArticleActivity
import com.ziq.zcamp.post.PublishDynamicActivity
import com.ziq.zcamp.post.PublishVideoActivity
import com.ziq.zcamp.util.PermissionHelper
import com.ziq.zcamp.util.PictureUtil
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object PostManager {

    var currentPostType = -1
    val uploadStatus = MutableLiveData<Int>(0)
    val process = MutableLiveData<Int>(0)
    val postEditSuccessId = MutableLiveData<String>("")

    const val POST_TYPE_DYNAMIC = 1
    const val POST_TYPE_VIDEO = 2
    const val POST_TYPE_ARTICLE = 3

    const val UPLOAD_STATUS_IDLE = 0
    const val UPLOAD_STATUS_START = 1
    const val UPLOAD_STATUS_SUCCESS = 2
    const val UPLOAD_STATUS_FAIL = 3

    val subjectList = MutableLiveData<List<PostSubject>>()


    fun showPostTypeSelector(activity: FragmentActivity, campInfo: CampInfo? = null, dismissListener :(()->Unit)? = null){
        val dialog = PostTypeSelectorDialog.Builder(activity).setCallback(object :
            PostTypeSelectorDialog.ActionCallBack {
            override fun onActionClick(
                dialog: PostTypeSelectorDialog,
                position: Int
            ) {
                dialog.dialogDismiss()
                when(position){
                    0->{
                        PermissionHelper.requestStoragePermission(activity, onGrant = {
                            publishDynamic(activity,campInfo = campInfo)
                        })
                    }
                    1->{
                        PermissionHelper.requestStoragePermission(activity, onGrant = {
                            publishVideo(activity, campInfo = campInfo)
                        })
                    }
                    2->{
                        PermissionHelper.requestStoragePermission(activity, onGrant = {
                            publishArticle(activity, campInfo = campInfo)
                        })
                    }
                }
            }

        }).build()
        dialog.setOnDismissListener {
            dismissListener?.invoke()
        }
        dialog.show()
    }

    private fun publishDynamic(activity: Activity, campInfo: CampInfo? = null){
        PictureUtil.selectPicture(activity,  emptyList(), object :
            OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                val list = ArrayList<PostMedia>()
                if(result != null){
                    for (item in result!!){
                        list.add(PostMedia().apply { localMedia = item })
                    }
                }
                PublishDynamicActivity.startActivity(activity, list, campInfo = campInfo)
            }

            override fun onCancel() {

            }
        })
    }

    private fun publishVideo(activity: Activity, campInfo: CampInfo? = null){
        when(uploadStatus.value){
            UPLOAD_STATUS_FAIL->{
                if(currentPostType == POST_TYPE_VIDEO){
                    PublishVideoActivity.startActivity(activity, ArrayList<PostMedia>(), isFail = true)
                } else {
                    selectVideoAndPublish(activity, campInfo)
                }
            }
            UPLOAD_STATUS_START->{
                Toast.makeText(GlobalContextManager.appContext, "当前已有内容正在发布中，请稍安勿躁~", Toast.LENGTH_SHORT).show()
            }
            else ->{
                selectVideoAndPublish(activity, campInfo)
            }
        }
    }

    private fun selectVideoAndPublish(activity: Activity, campInfo: CampInfo? = null){
        PictureUtil.selectVideo(activity,  emptyList(), object :
            OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                val list = ArrayList<PostMedia>()
                if(result != null){
                    for (item in result){
                        list.add(PostMedia().apply { localMedia = item })
                    }
                }
                PublishVideoActivity.startActivity(activity, list, campInfo = campInfo)
            }

            override fun onCancel() {

            }
        })
    }

    private fun publishArticle(activity: Activity, campInfo: CampInfo? = null){
        when(uploadStatus.value){
            UPLOAD_STATUS_FAIL->{
                if(currentPostType == POST_TYPE_ARTICLE){
                    PublishArticleActivity.startActivity(activity, campInfo = campInfo, isFail = true)
                } else {
                    PublishArticleActivity.startActivity(activity, campInfo = campInfo)
                }
            }
            UPLOAD_STATUS_START->{
                Toast.makeText(GlobalContextManager.appContext, "当前已有内容正在发布中，请稍安勿躁~", Toast.LENGTH_SHORT).show()
            }
            else ->{
                PublishArticleActivity.startActivity(activity, campInfo = campInfo)
            }
        }
    }


    fun getCoverPath():String{
        var path = ""
//        if(currentPostType == POST_TYPE_VIDEO){
//            if(PublishVideoManager.video != null){
//                path = PublishVideoManager.video!!.getUrl()
//            }
//            if(PublishVideoManager.videoCover != null){
//                path = PublishVideoManager.videoCover!!.getUrl()
//            }
//        } else if(currentPostType == POST_TYPE_ARTICLE){
//            if(PublishArticleManager.coverMedia != null){
//                path = PublishArticleManager.coverMedia!!.getUrl()
//            }
//        }
        return path
    }


    fun navigateToDetailActivity(context: Context, item: PostingDetail, comment : CommentItem? = null){
        navigateToDetailActivityForType(context, item.post?.p_type?:1, "${item.post?.post_id?:0}", item.user?.uid?:0, comment = comment)
    }

    fun navigateToDetailActivityForType(context: Context, type: Int, postId:String, createUid :Int, comment : CommentItem? = null, item: PostingDetail? = null){
        when(type){
            POST_TYPE_DYNAMIC->{
                DynamicDetailActivity.open(context, postId, createUid, comment = comment, detail = item)
            }
//            POST_TYPE_VIDEO->{
//                VideoDetailActivity.open(context, postId, createUid, source, comment = comment, detail = item)
//            }
//            POST_TYPE_ARTICLE->{
//                ArticleDetailActivity.open(context, postId, createUid, source, comment = comment, detail = item)
//            }
            else->{
                DynamicDetailActivity.open(context, postId, createUid, comment = comment, detail = item)
            }
        }
    }


    fun requestSubject(
        onSuccess: ((result: PostSubjectListRespond) -> Unit)? = {
            val resultList = mutableListOf<PostSubject>()
            resultList.addAll(it.data?.list?: listOf())
            subjectList.postValue(resultList)
        },
        onFail: ((result: String) -> Unit)? = {
        }) {
        launchWithTryAsyncGlobal(whenTry = {
            val entryPoint = EntryPointAccessors.fromApplication(
                GlobalContextManager.appContext!!,
                ServiceEntryPointManager::class.java
            )
            val respond = entryPoint.postingService().postSubjectList(PostSubjectListParam().queryMap).request()

            if(respond.data?.list?.isNotEmpty() == true){
                for(item in respond.data?.list!!){
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (item.pictures?.isNotEmpty() == true){
                        item.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(
                                ImageInfo::class.java))
                        }
                    }
                    item.images = imageList
                }
            }

            withContext(Dispatchers.Main){
                onSuccess?.invoke(respond)
            }
        }, whenCatch = {
            withContext(Dispatchers.Main){
                onFail?.invoke("$it")
            }
        })

    }

    fun postRecord(postId: String,post_uid :String) {
        launchWithTryAsyncGlobal(whenTry = {
            val entryPoint = EntryPointAccessors.fromApplication(
                GlobalContextManager.appContext!!,
                ServiceEntryPointManager::class.java
            )
            entryPoint.postingService().postingRecord(PostingRecordParam().apply {
                this.post_id = postId
                this.create_uid = post_uid
            }).request()
        })
    }


}